import cheerio from "cheerio";
import http from "http";
import iconv from "iconv-lite";

const searchReagentByCas = (casno: string) => {
  return new Promise((resolve, reject) => {
    http.get(`http://www.ichemistry.cn/chemistry/${casno}.htm`, (res) => {
      let body: any = [];
      res.on("data", function (chunk) {
        body.push(chunk);
      });
      res.on("end", function () {
        let html = iconv.decode(Buffer.concat(body), "gb2312");
        let $ = cheerio.load(html);
        let reObj: any = null;
        try {
          if ($("table.ChemicalInfo tr").length) {
            reObj = {};
            $("table.ChemicalInfo tr").each((index, item) => {
              const titleStr: string = $(item).find("td.ltd").text();
              if (titleStr.indexOf("中文名") >= 0) {
                // const cnnameStr: string = $($(item).find("td")[1]).text();
                reObj.cnname = $($(item).find("td")[1]).text();
              }
              if (titleStr.indexOf("英文名") >= 0) {
                // const ennameStr: string = $($(item).find("td")[1]).text();
                reObj.enname = $($(item).find("td")[1]).text();
              }
              if (titleStr.indexOf("分子式") >= 0) {
                // const formulaStr: string = $($(item).find("td")[1]).text();
                reObj.formula = $($(item).find("td")[1]).text();
              }
              if (titleStr.indexOf("性质描述") >= 0) {
                // const descStr: string = $($(item).find("td")[1]).text();
                reObj.desc = $($(item).find("td")[1]).text();
              }
              if (titleStr.indexOf("分子量") >= 0) {
                reObj.mw = $($(item).find("td")[1]).text();
              }
              if (titleStr.indexOf("密度") >= 0) {
                reObj.density = $($(item).find("td")[1]).text();
              }
              if (titleStr.indexOf("分子结构") >= 0) {
                reObj.structural = $($($(item).find("td")[1]).find("img")).attr(
                  "src"
                );
              }
              if (titleStr.indexOf("熔点") >= 0) {
                reObj.mp = $($(item).find("td")[1]).text();
              }
              if (titleStr.indexOf("沸点") >= 0) {
                reObj.bp = $($(item).find("td")[1]).text();
              }
            });
          }
        } catch (e) {
          reject(e);
        }
        resolve(reObj);
      });
    });
  });
};

export default searchReagentByCas;
